/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets.gp;

import be.ugent.medirem.logic.PatientRemote;
import be.ugent.medirem.persistence.exception.EntityNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Simon
 */
public class GpFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            Long id = (Long) ((HttpServletRequest)request).getSession().getAttribute("pid");
            if (id != null && id != 0) {
                request.setAttribute("patientid", id);
                try {
                    request.setAttribute("patientname", lookupPatientBean().getPatientDetails(id).getName());
                } catch (EntityNotFoundException ex) {
                    Logger.getLogger(GpFilter.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(GpFilter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    private PatientRemote lookupPatientBean() {
        try {
            Context c = new InitialContext();
            return (PatientRemote) c.lookup("java:comp/env/PatientBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
